"""
会员系统前端组件
提供会员信息展示、特权查看、升级进度等界面
"""

import streamlit as st
from datetime import datetime, timedelta
try:
    from utils.membership_system import (
        get_user_membership, 
        get_next_level_requirements,
        check_vip_status,
        MEMBERSHIP_LEVELS
    )
    MEMBERSHIP_SYSTEM_AVAILABLE = True
except ImportError:
    MEMBERSHIP_SYSTEM_AVAILABLE = False
    print("会员系统模块导入失败")

def render_membership_badge(level: str, is_vip: bool = False) -> str:
    """渲染会员等级徽章"""
    if not MEMBERSHIP_SYSTEM_AVAILABLE:
        return ""
    
    level_info = MEMBERSHIP_LEVELS.get(level, MEMBERSHIP_LEVELS["bronze"])
    vip_tag = " VIP" if is_vip else ""
    
    return f"""
    <div style="
        display: inline-flex;
        align-items: center;
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        border: 2px solid #ffa500;
        border-radius: 20px;
        padding: 5px 15px;
        margin: 5px;
        box-shadow: 0 2px 8px rgba(255, 165, 0, 0.3);
        font-weight: bold;
        color: #8b4513;
    ">
        <span style="font-size: 1.2em; margin-right: 5px;">{level_info["icon"]}</span>
        <span>{level_info["name"]}{vip_tag}</span>
    </div>
    """

def render_progress_bar(current: float, target: float, label: str, color: str = "#ff6b6b") -> str:
    """渲染进度条"""
    # 确保数值类型正确
    current = float(current) if current is not None else 0.0
    target = float(target) if target is not None else 1.0
    
    if target <= 0:
        percentage = 100
    else:
        percentage = min((current / target) * 100, 100)
    
    # 格式化显示值 - 如果是整数则显示为整数，否则显示小数
    current_display = f"{current:.0f}" if current.is_integer() else f"{current:.1f}"
    target_display = f"{target:.0f}" if target.is_integer() else f"{target:.1f}"
    
    return f"""
    <div style="margin: 10px 0;">
        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
            <span style="font-weight: bold; color: #333;">{label}</span>
            <span style="color: #666;">{current_display}/{target_display}</span>
        </div>
        <div style="
            width: 100%;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            height: 10px;
        ">
            <div style="
                width: {percentage}%;
                background: linear-gradient(90deg, {color}, {color}cc);
                height: 100%;
                border-radius: 10px;
                transition: width 0.3s ease;
            "></div>
        </div>
        <div style="text-align: right; font-size: 0.8em; color: #888; margin-top: 2px;">
            {percentage:.1f}%
        </div>
    </div>
    """

def show_membership_center(user_id: str):
    """显示会员中心主界面"""
    if not MEMBERSHIP_SYSTEM_AVAILABLE:
        st.error("会员系统暂时不可用")
        return
    
    st.markdown("""
    <style>
    .membership-container {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 20px;
        margin: 20px 0;
        color: white;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    }
    .benefit-card {
        background: white;
        border-radius: 15px;
        padding: 15px;
        margin: 10px 0;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        border-left: 5px solid #667eea;
    }
    .stats-card {
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        border-radius: 15px;
        padding: 20px;
        margin: 10px;
        text-align: center;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    </style>
    """, unsafe_allow_html=True)
    
    # 获取用户会员信息
    membership = get_user_membership(user_id)
    is_vip = check_vip_status(user_id)
    
    # 会员等级展示区域
    st.markdown('<div class="membership-container">', unsafe_allow_html=True)
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown(f"## 👋 您好，尊贵的会员！")
        badge_html = render_membership_badge(membership["level"], is_vip)
        st.markdown(badge_html, unsafe_allow_html=True)
        
        # VIP状态提示
        if is_vip:
            vip_expires = membership.get("vip_expires")
            if vip_expires:
                expires_date = datetime.fromisoformat(vip_expires)
                days_left = (expires_date - datetime.now()).days
                st.success(f"🌟 VIP特权有效期还有 {days_left} 天")
    
    with col2:
        # 会员统计信息
        st.markdown(f"""
        <div class="stats-card">
            <h4>📊 会员数据</h4>
            <p><strong>积分：</strong>{membership.get('points_earned', 0)}</p>
            <p><strong>订单：</strong>{membership.get('total_orders', 0)}</p>
            <p><strong>消费：</strong>¥{membership.get('total_spending', 0):.2f}</p>
        </div>
        """, unsafe_allow_html=True)
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    # 标签页导航
    tab1, tab2, tab3 = st.tabs(["🎯 升级进度", "🎁 会员特权", "📈 成长记录"])
    
    with tab1:
        show_upgrade_progress(user_id)
    
    with tab2:
        show_membership_benefits(user_id)
    
    with tab3:
        show_membership_history(user_id)

def show_upgrade_progress(user_id: str):
    """显示升级进度"""
    requirements = get_next_level_requirements(user_id)
    
    if requirements.get("is_max_level"):
        st.success("🎉 恭喜您！您已达到最高会员等级！")
        st.balloons()
        return
    
    st.markdown(f"### 🚀 升级到 {requirements['next_level_icon']} {requirements['next_level_name']}")
    
    # 进度条
    current = requirements["current_progress"]
    needed = requirements["requirements"]
    targets = requirements.get("next_level_targets", {})
    
    # 积分进度
    if needed["points_needed"] > 0:
        target_points = targets.get("points", current["points"] + needed["points_needed"])
        points_progress = render_progress_bar(
            current["points"], 
            target_points,
            f"积分进度 (还需{needed['points_needed']}积分)",
            "#ff6b6b"
        )
        st.markdown(points_progress, unsafe_allow_html=True)
    else:
        st.success("✅ 积分要求已达成")
    
    # 订单进度
    if needed["orders_needed"] > 0:
        target_orders = targets.get("orders", current["orders"] + needed["orders_needed"])
        orders_progress = render_progress_bar(
            current["orders"],
            target_orders,
            f"订单进度 (还需{needed['orders_needed']}个订单)",
            "#4ecdc4"
        )
        st.markdown(orders_progress, unsafe_allow_html=True)
    else:
        st.success("✅ 订单要求已达成")
    
    # 消费进度
    if needed["spending_needed"] > 0:
        target_spending = targets.get("spending", current["spending"] + needed["spending_needed"])
        spending_progress = render_progress_bar(
            current["spending"],
            target_spending,
            f"消费进度 (还需¥{needed['spending_needed']:.2f})",
            "#45b7d1"
        )
        st.markdown(spending_progress, unsafe_allow_html=True)
    else:
        st.success("✅ 消费要求已达成")
    
    # 下一等级特权预览
    if requirements.get("next_benefits"):
        st.markdown("#### 🎁 升级后享受的新特权：")
        benefits = requirements["next_benefits"]
        
        col1, col2 = st.columns(2)
        
        with col1:
            if benefits.get("discount_rate", 0) > 0:
                st.info(f"💰 购物折扣：{benefits['discount_rate']*100:.0f}%")
            
            if benefits.get("free_shipping_threshold", 999) < 999:
                threshold = benefits["free_shipping_threshold"]
                if threshold == 0:
                    st.info("🚚 免费配送：所有订单免运费")
                else:
                    st.info(f"🚚 免运费门槛：满¥{threshold}元")
        
        with col2:
            if benefits.get("points_multiplier", 1) > 1:
                st.info(f"⭐ 积分倍率：{benefits['points_multiplier']}倍")
            
            if benefits.get("monthly_coupons", 0) > 0:
                st.info(f"🎫 月度优惠券：{benefits['monthly_coupons']}张")

def show_membership_benefits(user_id: str):
    """显示会员特权"""
    membership = get_user_membership(user_id)
    benefits = membership["benefits"]
    
    st.markdown("### 🎁 您当前享受的会员特权")
    
    # 特权卡片网格
    col1, col2 = st.columns(2)
    
    with col1:
        # 购物优惠
        if benefits.get("discount_rate", 0) > 0:
            st.markdown(f"""
            <div class="benefit-card">
                <h4>💰 购物折扣</h4>
                <p style="color: #ff6b6b; font-size: 1.5em; font-weight: bold;">
                    {benefits['discount_rate']*100:.0f}% OFF
                </p>
                <p style="color: #666;">购买任意商品享受折扣</p>
            </div>
            """, unsafe_allow_html=True)
        
        # 免运费
        threshold = benefits.get("free_shipping_threshold", 99)
        if threshold == 0:
            shipping_text = "所有订单免运费"
            threshold_text = "🆓"
        else:
            shipping_text = f"满¥{threshold}元免运费"
            threshold_text = f"¥{threshold}"
        
        st.markdown(f"""
        <div class="benefit-card">
            <h4>🚚 配送特权</h4>
            <p style="color: #4ecdc4; font-size: 1.5em; font-weight: bold;">
                {threshold_text}
            </p>
            <p style="color: #666;">{shipping_text}</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        # 积分倍率
        multiplier = benefits.get("points_multiplier", 1)
        st.markdown(f"""
        <div class="benefit-card">
            <h4>⭐ 积分特权</h4>
            <p style="color: #45b7d1; font-size: 1.5em; font-weight: bold;">
                {multiplier}倍积分
            </p>
            <p style="color: #666;">购物获得更多积分</p>
        </div>
        """, unsafe_allow_html=True)
        
        # 月度优惠券
        monthly_coupons = benefits.get("monthly_coupons", 0)
        if monthly_coupons > 0:
            st.markdown(f"""
            <div class="benefit-card">
                <h4>🎫 优惠券特权</h4>
                <p style="color: #667eea; font-size: 1.5em; font-weight: bold;">
                    {monthly_coupons}张/月
                </p>
                <p style="color: #666;">每月自动发放优惠券</p>
            </div>
            """, unsafe_allow_html=True)

def show_membership_history(user_id: str):
    """显示会员成长记录"""
    st.markdown("### 📈 我的成长记录")
    
    membership = get_user_membership(user_id)
    
    # 成长时间线
    joined_date = datetime.fromisoformat(membership.get("joined_date", datetime.now().isoformat()))
    last_upgrade = datetime.fromisoformat(membership.get("last_upgrade", datetime.now().isoformat()))
    
    st.markdown(f"""
    <div style="
        background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
        border-radius: 15px;
        padding: 20px;
        margin: 15px 0;
    ">
        <h4>🕒 成长时间线</h4>
        <div style="margin: 10px 0;">
            <strong>📅 加入时间：</strong>{joined_date.strftime('%Y年%m月%d日')}
        </div>
        <div style="margin: 10px 0;">
            <strong>🚀 最近升级：</strong>{last_upgrade.strftime('%Y年%m月%d日')}
        </div>
        <div style="margin: 10px 0;">
            <strong>⏱️ 会员天数：</strong>{(datetime.now() - joined_date).days}天
        </div>
    </div>
    """, unsafe_allow_html=True)
    
    # 成就展示
    achievements = []
    points = membership.get("points_earned", 0)
    orders = membership.get("total_orders", 0)
    spending = membership.get("total_spending", 0)
    
    if points >= 1000:
        achievements.append("🏆 积分达人 - 累计获得1000+积分")
    if orders >= 10:
        achievements.append("🛒 购物专家 - 完成10+订单")
    if spending >= 5000:
        achievements.append("💎 消费之星 - 累计消费5000+元")
    
    if achievements:
        st.markdown("#### 🎖️ 我的成就")
        for achievement in achievements:
            st.success(achievement)
    else:
        st.info("继续购物解锁更多成就吧！")

def show_compact_membership_info(user_id: str):
    """显示紧凑的会员信息（用于侧边栏等）"""
    if not MEMBERSHIP_SYSTEM_AVAILABLE:
        return
    
    try:
        membership = get_user_membership(user_id)
        is_vip = check_vip_status(user_id)
        
        # 会员徽章
        badge_html = render_membership_badge(membership["level"], is_vip)
        st.markdown(badge_html, unsafe_allow_html=True)
        
    except Exception as e:
        st.error(f"加载会员信息失败: {str(e)}")

def show_membership_discount_info(user_id: str, order_amount: float):
    """显示购买时的会员优惠信息"""
    if not MEMBERSHIP_SYSTEM_AVAILABLE:
        return
    
    try:
        from utils.membership_system import check_discount_eligibility, check_free_shipping_eligibility
        
        # 检查折扣
        discount_info = check_discount_eligibility(user_id, order_amount)
        if discount_info.get("eligible"):
            st.success(f"💎 会员优惠: 原价¥{discount_info['original_amount']:.2f} → 会员价¥{discount_info['final_amount']:.2f}")
            st.info(f"🎉 您享受{discount_info['level_name']}折扣，省¥{discount_info['discount_amount']:.2f}")
        
        # 检查免运费
        shipping_info = check_free_shipping_eligibility(user_id, order_amount)
        if shipping_info.get("eligible"):
            st.success(f"🚚 {shipping_info['level_name']}享受免运费特权")
        else:
            threshold = shipping_info.get("threshold", 99)
            if threshold < 999:
                st.info(f"🚚 再购买¥{threshold - order_amount:.2f}即可享受免运费")
    
    except Exception as e:
        print(f"显示会员优惠信息失败: {e}")
